import os

from conf.database import Database
from conf.settings import Settings


class LeaveRuleTable:
    def __init__(self, settings=None, filepath=None):
        self.TAG = '【放假规律表】'
        self.settings = settings
        self.filepath = filepath
        self.workbook = None

        if filepath is None:
            print(self.TAG, f'找不到文件【{self.filepath}】')
            return

        print(self.TAG, self.filepath)

        db_file_path = os.path.join(self.settings.db_path, self.settings.db_file)
        db_connect = Database.connect(db_file=db_file_path)
        drop_sql = 'drop table if exists leave_rule_table'
        Database.execute(db_connect=db_connect, sql=drop_sql)
        create_sql = 'create table if not exists leave_rule_table(id INTEGER PRIMARY KEY,\
        year INTEGER,month INTEGER,day INTEGER,status BOOLEAN,update_time DATETIME)'
        Database.execute(db_connect=db_connect, sql=create_sql)
        Database.close(db_connect)

    def error(self, message):
        self.settings.logger.error(message)

    def load(self, workbook):
        self.workbook = workbook

    def show(self):
        sheets = self.workbook.sheets
        sheet = sheets(1)

        rows = sheet.used_range.value
        for cols in rows:
            for cell in cols:
                print(cell, end=' ')
            print('')
        pass

    def close(self):
        self.workbook.close()
        pass

    def exec(self):
        db_file_path = os.path.join(self.settings.db_path, self.settings.db_file)
        db_connect = Database.connect(db_file=db_file_path)
        sheets = self.workbook.sheets
        sheet = sheets(1)
        rows = sheet.used_range.value
        year = self.settings.current_year
        for cols in rows[1:]:
            insert_sql = 'insert into leave_rule_table(year,month,day,status,update_time) values (?,?,?,?,?)'
            insert_data = [(year, int(cols[0]), index + 1, int(cols[1:-1][index]), Settings.get_datetime())
                           for index in range(len(cols[1:-1]))]
            Database.executemany(db_connect=db_connect, sql=insert_sql, data=insert_data)
        Database.close(db_connect=db_connect)
        pass
